package com.str.utils;

import com.alibaba.fastjson.JSONObject;
import com.str.pojo.SystemUser;
import com.str.vo.SystemUserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author ZhangWu, Anything is possible!
 * @date 2022/3/14 16:06
 * @description 公共帮助类
 */
@Slf4j
@Component
public class CommonUtil {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private static RedisUtil staticRedisUtil;

    @PostConstruct
    public void init() {
        staticRedisUtil = redisUtil;
    }


    /**
     * http请求返回json格式值
     * @param retcode 返回码
     * @param retmsg 返回值
     * @param data 返回数据
     * @return 返回json字符传
     */
    public static String returnJson(String retcode, String retmsg, Object data){
        try {
            JSONObject json = new JSONObject();
            json.put("retcode",retcode);
            json.put("retmsg",retmsg);
            json.put("data",data);
            String content = json.toString();
            return content;
        } catch (Exception e) {
            log.error("请求响应出错Exception",e);
        }
        return null;
    }
    /**
     * 获取登录的企业用户信息
     * @param request
     * @return
     */
    public static SystemUserVO getSystemUser(HttpServletRequest request){
        String token = request.getHeader("X-Token");
        if (StringUtils.isBlank(token)){
            throw new RuntimeException("登录已过期，请重新登录！");
        }
        return staticRedisUtil.get(token,SystemUserVO.class);
    }

    /**
     * 获取系统配置，首先获取企业级的，如果企业级的获取不到获取系统默认级别的
     * @param key 配置key
     * @param enterpriseId 企业ID
     * @return
     */
    public static String getSystemConfigValue(String key,String enterpriseId){
        if(StringUtils.isEmpty(key)){
            return null;
        }

        if(!StringUtils.isNotEmpty(enterpriseId)){
            String enterpriseKey = key+"_"+enterpriseId;
            String enterpriseValue = staticRedisUtil.get(enterpriseKey,String.class);
            if(StringUtils.isNotEmpty(enterpriseValue)){
                return enterpriseValue;
            }
        }
        return staticRedisUtil.get(key,String.class);
    }

    /**
     * 获取一个uuid
     * @return
     */
    public static String uuid(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }

}
